/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;


public class ControlAudioJuego{

    private static final int EXTERNAL_BUFFER_SIZE = 128000;
    public SourceDataLine line = null;
    public String ruta = null;
    public boolean play = true;
    
    public void reproducir(String rutaArchivoSonido){
        while(play){
            reproducirSonido(rutaArchivoSonido);
        }
    }
    
    private void reproducirSonido(String rutaArchivoSonido) {
        File soundFile = new File(rutaArchivoSonido);
        AudioInputStream audioInputStream = null;
        try {
            audioInputStream = AudioSystem.getAudioInputStream(soundFile);
            AudioFormat audioFormat = audioInputStream.getFormat();
            DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                    audioFormat);
            line = (SourceDataLine) AudioSystem.getLine(info);
            line.open(audioFormat);

            line.start();
            
            int nBytesRead = 0;
            byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
            
            while (nBytesRead != -1) {
                nBytesRead = audioInputStream.read(abData, 0, abData.length);
                if (nBytesRead >= 0) {
                    int nBytesWritten = line.write(abData, 0, nBytesRead);
                    
                }
            }
            //line.drain();
            line.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    public void detener() {
        play = false;
        line.close();
    }

}
